package net.xdclass.base_project.producer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * @author sqz
 * @Description: kafka发送
 * @date 2019/9/23 16:38
 */
@Component
public class KafkaSender {

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    private final Logger logger = LoggerFactory.getLogger(KafkaSender.class);

    public void send(String topic,String taskId,String jsonStr){
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, taskId, jsonStr);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            //推送失败
            @Override
            public void onFailure(Throwable ex) {
                logger.info(topic + " 生产者发送消息失败：" + ex.getMessage());
            }
            //推送成功
            @Override
            public void onSuccess(SendResult<String, Object> result) {
                logger.info("patition是:{},offset是:{},消息内容是:{}",result.getRecordMetadata().partition(),result.getRecordMetadata().offset(),jsonStr);
            }
        });
    }
}
